<!--日志详情-->
<template>
  <div class="log-details">
    <el-form :inline="true" class="search-form">
      <el-row>
        <el-col :span="6">
          <el-form-item label="协议类型" class="search-select">
            <el-select v-model="form.protocol" style="width: 200px">
              <el-option
                v-for="item in protocolOptions"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="日志类型" class="search-select">
            <el-select v-model="form.logType" style="width: 200px">
              <el-option
                v-for="item in logTypeOptions"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="6">
          <el-form-item label="属性" class="search-select">
            <el-select v-model="form.deviceStateAndSignal" style="width: 200px" :disabled="!exist || form.logType !== 'properties'">
              <el-option
                v-for="item in attributeOptions"
                :key="item.dpId"
                :label="item.dpName"
                :value="item.dpId"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="起始时间">
            <el-date-picker
              v-model="form.startDateTime"
              type="datetime"
              placeholder="开始时间"
              format="yyyy/MM/dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              :disabled-date="disabledStartDate"
              :disabled-time="disabledStartTime"
              :clearable="false"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="form.endDateTime"
              type="datetime"
              placeholder="结束时间"
              format="yyyy/MM/dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              :disabled-date="disabledEndDate"
              :disabled-time="disabledEndTime"
              :clearable="false"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" size="14" @click="resetSearch">重置</el-button>
          <!-- <el-button type="primary" size="14" @click="exportLogs">导出日志</el-button> -->
          <el-button type="primary" size="14" @click="loadList">查询</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{ background: '#F5F6F7' }"
      size="medium"
    >
      <el-table-column
        type="index"
        label="序号"
        width="80">
      </el-table-column>

      <el-table-column
        prop="createTime"
        label="时间(GMT+8)">
      </el-table-column>

      <el-table-column
        prop="deviceName"
        label="设备名称">
      </el-table-column>

      <el-table-column
        prop="deviceId"
        label="设备ID">
      </el-table-column>

      <el-table-column
        prop="protocolLogType"
        label="协议类型">
        <template slot-scope="scope">
          <el-tooltip
            effect="light"
            trigger="click"
            placement="top"
            :open-delay="200"
            popper-class="custom-tooltip">
            <div slot="content">
              <div v-if="scope.row.protocolLogType === 'http'">
                <div><span class="title">httpUrl：</span>{{ scope.row.httpUrl }}</div>
                <div><span class="title">requestMethod：</span>{{ scope.row.requestMethod }}</div>
                <div><span class="title">requestParam：</span>{{ scope.row.requestParam }}</div>
                <div><span class="title">responseParam：</span>{{ scope.row.responseParam ? scope.row.responseParam.slice(0, 2000) : '-' }}...</div>
              </div>
              <div v-else-if="scope.row.protocolLogType === 'mqtt'">
                <div><span class="title">payload：</span>{{ scope.row.payload }}</div>
                <div><span class="title">topic：</span>{{ scope.row.topic }}</div>
              </div>
            </div>
            <span>{{ scope.row.protocolLogType }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        prop="mqttTime"
        label="报文时间"
      />
      <el-table-column
        prop="eventName"
        label="事件名称">
      </el-table-column>

      <el-table-column
        prop="evenContent"
        label="事件详情"
        :min-width="150">
      </el-table-column>

      <el-table-column
        prop="eventSource"
        label="事件来源">
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import minMax from 'dayjs/plugin/minMax'
import { getProperties, logDetailsList } from '@/api/device/log2'
dayjs.extend(minMax)

export default {
  name: 'LogDetails',
  props: {
    exist: {
      type: Boolean,
      default: false
    },
    deviceIdOrUid: {
      type: String,
      default: ''
    },
    deviceId: {
      type: String,
      default: ''
    },
    queryInfo: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    const now = dayjs()
    return {
      form: {
        protocol: '', // 协议类型
        logType: '', // 日志类型
        deviceStateAndSignal: '',
        startDateTime: now.subtract(12, 'hour').format('YYYY-MM-DD HH:mm'),
        endDateTime: now.format('YYYY-MM-DD HH:mm')
      },
      protocolOptions: [
        { key: 'mqtt', label: 'MQTT' },
        { key: 'http', label: 'HTTP' },
        { key: '', label: '全部' }
      ],
      logTypeOptions: [
        { key: '', label: '全部' },
        { key: 'line', label: '设备上下线' },
        { key: 'properties', label: '属性上报下发' }
      ],
      // attributeOptions: [], // 属性列表
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false
    }
  },
  // watch: {
  //   'form.startDateTime'(val) {
  //     const start = dayjs(val)
  //     const end = dayjs(this.form.endDateTime)
  //     const maxEnd = dayjs.min(start.add(3, 'day'), dayjs().endOf('day'))

  //     if (end.isBefore(start) || end.isAfter(maxEnd)) {
  //       this.form.endDateTime = start.add(12, 'hour').format('YYYY-MM-DD HH:mm')
  //     }
  //   },
  //   'form.endDateTime'(val) {
  //     const end = dayjs(val)
  //     const todayEnd = dayjs().endOf('day')

  //     if (end.isAfter(todayEnd)) {
  //       this.form.endDateTime = todayEnd.format('YYYY-MM-DD HH:mm')
  //     }

  //     const start = dayjs(this.form.startDateTime)
  //     if (start.isAfter(end) || start.isBefore(end.subtract(3, 'day'))) {
  //       this.form.startDateTime = end.subtract(12, 'hour').format('YYYY-MM-DD HH:mm')
  //     }
  //   }
  // },
  mounted() {
    // this.loadList()
  },
  methods: {
    async loadList() {
      this.loading = true
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        deviceIdOrUid: this.deviceId,
        ...this.form,
        deviceStateAndSignal: this.form.deviceStateAndSignal === '全部' ? '' : this.form.deviceStateAndSignal, // 属性选项
        startDateTime: this.form.startDateTime + ':00',
        endDateTime: this.form.endDateTime + ':59'
      }

      logDetailsList(params).then(res => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },

    // async queryProperties() {
    //   const params = {
    //     deviceId: this.deviceId
    //   }
    //   const res = await getProperties(params)
    //   if (res.code === 0) {
    //     this.attributeOptions = res.data
    //     this.attributeOptions.unshift({
    //       dpId: '全部',
    //       dpName: '全部'
    //     })
    //   }
    // },

    handleLogType() {
      this.form.deviceStateAndSignal = ''
      this.loadList()
    },

    resetSearch() {
      this.form.protocolType = ''
      this.form.logType = ''
      this.form.deviceStateAndSignal = ''
      this.form.startDateTime = dayjs().subtract(12, 'hour').format('YYYY-MM-DD HH:mm')
      this.form.endDateTime = dayjs().format('YYYY-MM-DD HH:mm')
      this.loadList()
    },
    exportLogs() {
      console.log('导出日志')
    },
    // 起始日期限制：只能选择结束时间往前3天内
    disabledStartDate(date) {
      if (!this.form.endDateTime) return false
      const end = dayjs(this.form.endDateTime)
      const threeDaysAgo = end.subtract(3, 'day')
      const now = dayjs().endOf('day')
      return (
        date.getTime() < threeDaysAgo.toDate().getTime() ||
        date.getTime() > end.toDate().getTime() ||
        date.getTime() > now.toDate().getTime()
      )
    },
    // 结束日期限制：只能选择起始时间之后，3天之内，不超过今天
    disabledEndDate(date) {
      if (!this.form.startDateTime) return false
      const start = dayjs(this.form.startDateTime)
      const threeDaysLater = dayjs.min(start.add(3, 'day'), dayjs().endOf('day'))
      return (
        date.getTime() < start.toDate().getTime() ||
        date.getTime() > threeDaysLater.toDate().getTime()
      )
    },
    // 起始时间小时/分钟限制
    disabledStartTime() {
      const end = dayjs(this.form.endDateTime)
      const min = end.subtract(3, 'day')
      const max = end
      return this.getDisabledTimeRange(min, max)
    },

    // 结束时间小时/分钟限制
    disabledEndTime() {
      const start = dayjs(this.form.startDateTime)
      const now = dayjs()
      const min = start
      const max = dayjs.min(start.add(3, 'day'), now.endOf('day'))
      return this.getDisabledTimeRange(min, max)
    },
    // 获取禁用小时/分钟的方法
    getDisabledTimeRange(min, max) {
      return {
        disabledHours: () => {
          const hours = []
          for (let i = 0; i < 24; i++) {
            const test = dayjs().hour(i).minute(0)
            if (test.isBefore(min, 'hour') || test.isAfter(max, 'hour')) {
              hours.push(i)
            }
          }
          return hours
        },
        disabledMinutes: (hour) => {
          const minutes = []
          for (let i = 0; i < 60; i++) {
            const test = dayjs().hour(hour).minute(i)
            if (test.isBefore(min, 'minute') || test.isAfter(max, 'minute')) {
              minutes.push(i)
            }
          }
          return minutes
        }
      }
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.loadList()()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.loadList()()
    }
  }
}
</script>

<style scoped lang="scss">
/* 可添加样式 */
</style>
